<template>
  <div class="chat-window">
    <div class="chat-header">
      <div class="header-left">
        <el-select v-model="selectedAssistantId" placeholder="请选择智能客服" @change="onAssistantChange" style="width: 220px;">
          <el-option v-for="assistant in assistants" :key="assistant.id" :label="assistant.name" :value="assistant.id" />
        </el-select>
      </div>
      <div class="header-right">
        <el-button @click="clearCurrentChat" type="warning" size="small">
          <el-icon><Delete /></el-icon>
          清空当前对话
        </el-button>
      </div>
    </div>
    <div class="chat-container">
      <div class="message-list" ref="messaggListRef">
        <div
          v-for="(message, index) in messages"
          :key="index"
          :class="
            message.isUser ? 'message user-message' : 'message bot-message'
          "
        >
          <!-- 会话图标 -->
          <i
            :class="
              message.isUser
                ? 'fa-solid fa-user message-icon'
                : 'fa-solid fa-robot message-icon'
            "
          ></i>
          <!-- 会话内容 -->
          <span>
            <span v-html="message.content"></span>
            <!-- loading -->
            <span
              class="loading-dots"
              v-if="message.isThinking || message.isTyping"
            >
              <span class="dot"></span>
              <span class="dot"></span>
            </span>
          </span>
        </div>
      </div>
      <div class="input-container">
        <el-button
          @click="toggleExpansionPanel"
          link
          :class="['expansion-button', { 'is-active': showExpansionPanel }]"
        >
          <i :class="showExpansionPanel ? 'fa-solid fa-minus' : 'fa-solid fa-plus'"></i>
        </el-button>
        <el-input
          v-model="inputMessage"
          placeholder="请输入消息"
          @keyup.enter="sendMessage"
        ></el-input>
        <el-button @click="sendMessage" :disabled="isSending" type="primary"
          >发送</el-button
        >
      </div>
      <div :class="['expansion-panel', { hidden: !showExpansionPanel }] ">
        <el-button @click="selectService" type="info" plain>智能客服选择</el-button>
        <el-button @click="uploadFile" type="info" plain>上传文件</el-button>
        <el-button @click="() => console.log('新的MCP工具按钮')" type="info" plain>新的MCP工具</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch, nextTick } from 'vue'
import axios from 'axios'
import { v4 as uuidv4 } from 'uuid'
import { useRoute } from 'vue-router'
import { Delete } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'

const route = useRoute()
const messaggListRef = ref()
const isSending = ref(false)
const showExpansionPanel = ref(false)
const uuid = ref(null) // memoryId
const sessionId = ref(null)
const inputMessage = ref('')
const messages = ref([])

// 智能客服相关
const assistants = ref([])
const selectedAssistantId = ref(null)
const assistantMap = ref({})

// 清空对话功能

onMounted(async () => {
  await loadAssistants()
  await loadSession()
  
  // 监听消息变化，自动滚动到底部
  watch(messages, () => scrollToBottom(), { deep: true })
  
  // 监听路由变化，切换会话时重新加载
  watch(() => route.query.id, async (newSessionId, oldSessionId) => {
    if (newSessionId && newSessionId !== oldSessionId) {
      console.log('会话切换:', oldSessionId, '->', newSessionId)
      
      // 当前会话已自动保存到后端
      
      // 切换到新会话 - 统一使用sessionId作为memoryId
      sessionId.value = newSessionId
      uuid.value = parseInt(newSessionId) || newSessionId  // 确保可以是数字或字符串
      
      await loadMessages()
      
      if (messages.value.length === 0) {
        await hello()
      }
      
      // 更新会话状态
      localStorage.setItem('current_chat_session', JSON.stringify({
        memoryId: uuid.value,
        sessionId: sessionId.value,
        assistantId: selectedAssistantId.value
      }))
    }
  }, { immediate: false })
  
  // 清理过期的本地存储数据（保留最近7天的数据）
  cleanOldLocalStorage()
})

// 清理过期的本地存储数据
const cleanOldLocalStorage = () => {
  const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000
  
  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i)
    if (key && key.startsWith('chat_history_')) {
      try {
        const data = JSON.parse(localStorage.getItem(key) || '[]')
        const hasRecentMessages = data.some(msg => {
          const msgTime = new Date(msg.timestamp).getTime()
          return msgTime > sevenDaysAgo
        })
        
        if (!hasRecentMessages && data.length > 0) {
          localStorage.removeItem(key)
          console.log('清理过期聊天记录:', key)
        }
      } catch (error) {
        // 如果解析失败，删除损坏的数据
        localStorage.removeItem(key)
      }
    }
  }
}

const loadAssistants = async () => {
  const res = await axios.get('/api/assistants')
  assistants.value = res.data
  assistantMap.value = Object.fromEntries(res.data.map(a => [a.id, a]))
}

const loadSession = async () => {
  // 1. 检查URL参数中的会话ID
  const urlSessionId = route.query.id
  
  console.log('URL会话ID:', urlSessionId)
  
  if (urlSessionId) {
    // 统一使用URL中的会话ID作为memoryId和sessionId
    sessionId.value = urlSessionId
    uuid.value = parseInt(urlSessionId) || urlSessionId  // 确保可以是数字或字符串
    
    // 从localStorage获取助手ID
    const localSession = JSON.parse(localStorage.getItem('current_chat_session') || '{}')
    if (localSession.sessionId === urlSessionId && localSession.assistantId) {
      selectedAssistantId.value = localSession.assistantId
    } else {
      selectedAssistantId.value = assistants.value.length > 0 ? assistants.value[0].id : null
    }
    
    // 从后端加载聊天记录
    await loadMessages()
    
    // 如果没有消息，显示欢迎语
    if (messages.value.length === 0) {
      await hello()
    }
    
    // 更新当前会话状态
    localStorage.setItem('current_chat_session', JSON.stringify({
      memoryId: uuid.value,
      sessionId: sessionId.value,
      assistantId: selectedAssistantId.value
    }))
  } else {
    // 2. 没有URL参数，尝试恢复上次会话
    const localSession = JSON.parse(localStorage.getItem('current_chat_session') || '{}')
    
    if (localSession.sessionId) {
      sessionId.value = localSession.sessionId
      uuid.value = localSession.memoryId || Date.now()
      selectedAssistantId.value = localSession.assistantId || (assistants.value.length > 0 ? assistants.value[0].id : null)
      
      await loadMessages()
      
      if (messages.value.length === 0) {
        await hello()
      }
    } else {
      // 3. 完全新的会话
      if (assistants.value.length > 0) {
        selectedAssistantId.value = assistants.value[0].id
        await createNewSession()
      }
    }
  }
}

const loadMessages = async () => {
  if (!uuid.value) return
  
  try {
    // 从后端获取聊天历史记录
    console.log(`从后端加载聊天记录，memoryId: ${uuid.value}`)
    const response = await axios.get(`/api/chat/history/${uuid.value}`)
    
    if (response.data && Array.isArray(response.data)) {
      messages.value = response.data.map(msg => ({
        content: msg.content,
        isUser: msg.isUser,
        isTyping: false,
        isThinking: false,
        timestamp: msg.timestamp || new Date().toISOString()
      }))
      console.log(`从后端加载了 ${messages.value.length} 条消息，memoryId: ${uuid.value}`)
    } else {
      messages.value = []
      console.log(`后端没有找到历史消息，memoryId: ${uuid.value}，使用空列表`)
    }
  } catch (error) {
    console.warn('从后端加载聊天记录失败，使用空列表:', error.message)
    messages.value = []
  }
}

const createNewSession = async () => {
  try {
    // 新建会话，后端返回sessionId和memoryId
    const res = await axios.post('/api/chat/session', { assistantId: selectedAssistantId.value })
    uuid.value = res.data.memoryId
    sessionId.value = res.data.sessionId
  } catch (error) {
    // 如果后端接口不存在，生成本地会话ID
    console.log('后端会话创建失败，使用本地会话')
    // 生成唯一的ID，sessionId和memoryId使用相同值
    const timestamp = Date.now()
    const random = Math.floor(Math.random() * 1000)
    const uniqueId = timestamp + random
    uuid.value = uniqueId
    sessionId.value = uniqueId.toString()  // 统一使用同一个ID
  }
  
  // 确保生成新的唯一会话
  console.log('创建新会话:', {
    memoryId: uuid.value,
    sessionId: sessionId.value,
    assistantId: selectedAssistantId.value
  })
  
  localStorage.setItem('current_chat_session', JSON.stringify({
    memoryId: uuid.value,
    sessionId: sessionId.value,
    assistantId: selectedAssistantId.value
  }))
  
  // 清空消息列表并显示欢迎语
  messages.value = []
  await hello()
}

const scrollToBottom = () => {
  if (messaggListRef.value) {
    messaggListRef.value.scrollTop = messaggListRef.value.scrollHeight
  }
}

const hello = async () => {
  // 发送当前客服的欢迎语
  const assistant = assistantMap.value[selectedAssistantId.value]
  console.log('当前选择的助手ID:', selectedAssistantId.value)
  console.log('助手信息:', assistant)
  
  // 优先使用助手的欢迎语，如果为空或不存在则使用默认欢迎语
  let welcomeMessage = '您好！我是您的智能客服助手，有什么可以帮助您的吗？' // 默认欢迎语
  
  if (assistant && assistant.welcomeMessage && assistant.welcomeMessage.trim()) {
    welcomeMessage = assistant.welcomeMessage
    console.log('使用助手欢迎语:', welcomeMessage)
  } else {
    console.log('使用默认欢迎语:', welcomeMessage)
  }
  
  // 检查是否已经有欢迎语了（避免重复添加）
  const hasWelcomeMessage = messages.value.some(msg => 
    !msg.isUser && (
      msg.content.includes('您好！我是您的智能客服助手') || 
      msg.content === welcomeMessage
    )
  )
  
  if (!hasWelcomeMessage) {
    const welcomeMsg = {
      isUser: false, 
      content: welcomeMessage, 
      isTyping: false, 
      isThinking: false,
      timestamp: new Date().toISOString()
    }
    messages.value.push(welcomeMsg)
    console.log('添加欢迎语到前端消息列表')
  } else {
    console.log('前端已有欢迎语，跳过添加')
  }
  
  // 将欢迎语保存到数据库，以便刷新页面后能显示
  if (uuid.value) {
    try {
      await axios.post(`/api/chat/init-welcome/${uuid.value}`, {
        welcomeMessage: welcomeMessage
      })
      console.log('欢迎语已保存到数据库')
    } catch (error) {
      console.warn('保存欢迎语到数据库失败:', error.message)
    }
  }
}

// 保存消息到本地存储
// 消息现在自动保存到后端MongoDB，不需要手动保存

const sendMessage = () => {
  // 检查是否选择了智能客服
  if (!selectedAssistantId.value) {
    ElMessageBox.alert(
      '请先选择一个智能客服才能开始对话。',
      '未选择智能客服',
      {
        confirmButtonText: '知道了',
        type: 'warning'
      }
    )
    return
  }
  
  if (inputMessage.value.trim()) {
    sendRequest(inputMessage.value.trim())
    inputMessage.value = ''
  }
}

const sendRequest = async (message) => {
  if (!selectedAssistantId.value) return
  isSending.value = true
  
  // 添加用户消息
  const userMsg = {
    isUser: true,
    content: message,
    isTyping: false,
    isThinking: false,
    timestamp: new Date().toISOString()
  }
  messages.value.push(userMsg)
  
  // 用户消息会通过LangChain4J自动保存到MongoDB
  
  // 添加AI回复占位消息
  const botMsg = {
    isUser: false,
    content: '',
    isTyping: true,
    isThinking: false,
    timestamp: new Date().toISOString()
  }
  messages.value.push(botMsg)
  const lastMsg = messages.value[messages.value.length - 1]
  scrollToBottom()

  // 处理memoryId格式
  let numericMemoryId = null
  if (uuid.value) {
    // 如果是UUID字符串，转换为数字
    if (typeof uuid.value === 'string') {
      numericMemoryId = uuidToNumber(uuid.value)
    } else {
      numericMemoryId = uuid.value
    }
  }
  
  const payload = { 
    message, 
    assistantId: selectedAssistantId.value, 
    memoryId: numericMemoryId 
  }
  
  console.log('发送聊天请求:', {
    原始memoryId: uuid.value,
    转换后memoryId: numericMemoryId,
    assistantId: selectedAssistantId.value,
    message: message.substring(0, 50) + '...'
  })
  try {
    const response = await axios.post(
      '/dianxiaoer/chat',
      payload,
      {
        responseType: 'text',
        onDownloadProgress: (e) => {
          const fullText = e.event.target.responseText
          let newText = fullText.substring(lastMsg.content.length)
          lastMsg.content += newText
          scrollToBottom()
          // AI回复内容会通过LangChain4J自动保存到MongoDB
        },
      }
    )
    
    // 完成AI回复
    messages.value.at(-1).isTyping = false
    messages.value.at(-1).timestamp = new Date().toISOString()
    isSending.value = false
    
    // 首次会话，后端返回新 memoryId
    if (!numericMemoryId && response && response.headers && response.headers['x-memory-id']) {
      uuid.value = Number(response.headers['x-memory-id'])
      localStorage.setItem('current_chat_session', JSON.stringify({
        memoryId: uuid.value,
        sessionId: sessionId.value,
        assistantId: selectedAssistantId.value
      }))
    }
    
    // 对话已通过LangChain4J自动保存到MongoDB
  } catch (error) {
    messages.value.at(-1).content = '请求失败，请重试'
    messages.value.at(-1).isTyping = false
    messages.value.at(-1).timestamp = new Date().toISOString()
    isSending.value = false
    // 错误信息也会保存到MongoDB
  }
}

const onAssistantChange = async (id) => {
  console.log('切换智能客服，从', selectedAssistantId.value, '到', id)
  selectedAssistantId.value = id
  
  // 更新当前会话的助手ID
  if (sessionId.value) {
    localStorage.setItem('current_chat_session', JSON.stringify({
      memoryId: uuid.value,
      sessionId: sessionId.value,
      assistantId: id
    }))
  }
  
  // 切换助手时创建新会话
  await createNewSession()
}

const uuidToNumber = (uuid) => {
  if (!uuid) return Date.now() % 1000000
  
  // 移除连字符，只保留十六进制字符
  const cleanUuid = uuid.toString().replace(/-/g, '')
  let number = 0
  
  // 取前6个字符转换为数字
  for (let i = 0; i < Math.min(cleanUuid.length, 6); i++) {
    const hexValue = cleanUuid[i]
    const digit = parseInt(hexValue, 16)
    if (!isNaN(digit)) {
      number = number * 16 + digit
    }
  }
  
  // 确保返回正数
  return Math.abs(number % 1000000) || Date.now() % 1000000
}

const convertStreamOutput = (output) => {
  return output
    .replace(/\n/g, '<br>')
    .replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
}

const toggleExpansionPanel = () => {
  showExpansionPanel.value = !showExpansionPanel.value
}

// 智能客服选择按钮：聚焦下拉框
const selectService = () => {
  document.querySelector('.chat-header .el-select input')?.focus()
}

const uploadFile = () => {
  console.log('文件上传功能待实现')
}

// 清空当前对话
const clearCurrentChat = async () => {
  // 如果只有欢迎语（1条消息）或没有消息，视为空对话
  if (messages.value.length <= 1) {
    console.log('当前对话已经是空的或只有欢迎语')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      '确定要清空当前对话吗？此操作将删除所有聊天记录且无法恢复。',
      '清空对话',
      {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 删除后端聊天记录
    if (uuid.value) {
      try {
        await axios.delete(`/api/chat/history/${uuid.value}`)
        console.log('已删除后端聊天记录，memoryId:', uuid.value)
      } catch (error) {
        console.warn('删除后端聊天记录失败:', error.message)
      }
    }
    
    // 清空消息列表
    messages.value = []
    
    // 生成新的会话ID，确保这是一个全新的会话
    const timestamp = Date.now()
    const random = Math.floor(Math.random() * 1000)
    uuid.value = timestamp + random
    sessionId.value = `session_${timestamp}_${Math.random().toString(36).substr(2, 9)}`
    
    // 更新本地存储
    localStorage.setItem('current_chat_session', JSON.stringify({
      memoryId: uuid.value,
      sessionId: sessionId.value,
      assistantId: selectedAssistantId.value
    }))
    
    // 重新显示欢迎语
    await hello()
    
    console.log('已清空当前对话，创建新会话:', sessionId.value)
  } catch {
    console.log('用户取消清空操作')
  }
}
</script>

<style scoped>
.chat-window {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: white;
  border-radius: 12px 12px 0 0;
  margin: 20px 20px 0 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  gap: 10px;
  align-items: center;
}

.chat-container {
  display: flex;
  flex-direction: column;
  flex: 1;
  background: white;
  border-radius: 0 0 12px 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin: 0 20px 20px 20px;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #fafafa;
  display: flex;
  flex-direction: column;
}

.message {
  margin-bottom: 15px;
  padding: 12px 16px;
  border-radius: 12px;
  display: flex;
  align-items: flex-start;
  max-width: 80%;
  word-wrap: break-word;
}

.user-message {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  align-self: flex-end;
  margin-left: auto;
}

.bot-message {
  background: white;
  color: #333;
  align-self: flex-start;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message-icon {
  margin-right: 10px;
  font-size: 1.2em;
  margin-top: 2px;
}

.user-message .message-icon {
  margin-right: 0;
  margin-left: 10px;
  order: 2;
}

.loading-dots {
  padding-left: 5px;
}

.dot {
  display: inline-block;
  margin-left: 5px;
  width: 8px;
  height: 8px;
  background-color: #000000;
  border-radius: 50%;
  animation: pulse 1.2s infinite ease-in-out both;
}

.dot:nth-child(2) {
  animation-delay: -0.6s;
}

@keyframes pulse {
  0%,
  100% {
    transform: scale(0.6);
    opacity: 0.4;
  }

  50% {
    transform: scale(1);
    opacity: 1;
  }
}

.input-container {
  display: flex;
  padding: 20px;
  background: white;
  border-top: 1px solid #e4e7ed;
  gap: 12px;
}

.input-container .el-input {
  flex: 1;
}

.input-container .el-button {
  min-width: 0px;
  height: 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  font-weight: 500;
}

.input-container .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.input-container .el-button:disabled {
  background: #c0c4cc;
  transform: none;
  box-shadow: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-window {
    padding: 0;
  }

  .message {
    max-width: 90%;
  }

  .input-container {
    padding: 15px;
  }
}

/* 滚动条样式 */
.message-list::-webkit-scrollbar {
  width: 6px;
  }

.message-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.message-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
  }

.message-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.expansion-button {
  font-size: 1.2em;
  color: #606266;
  transition: transform 0.3s ease;
  width: 40px; /* Make it circular */
  height: 40px; /* Make it circular */
  border-radius: 100%; /* Make it circular */
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0; /* Remove default padding to ensure pure circular shape */
  min-width: 0; /* Remove default min-width */
  background-color: #667eea; /* Solid background color for the circular button */
  border: 1px solid #667eea; /* Match border color to background */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* Slightly stronger shadow */
}

.expansion-button .fa-plus,
.expansion-button .fa-minus {
  transition: transform 0.3s ease;
  color: white; /* Change icon color to white */
}

.expansion-button.is-active .fa-plus {
  transform: rotate(45deg);
}

.expansion-panel {
  background: white;
  border-top: 1px solid #e4e7ed;
  padding: 10px 20px;
  display: flex;
  gap: 10px;
  justify-content: flex-start;
  align-items: center;
  transition: all 0.3s ease-out;
  overflow: hidden;
  height: auto; /* Allow content to dictate height */
  opacity: 1;
  transform: translateY(0);
}

/* Optionally add a class for when the panel is hidden to control height and opacity for animation */
.expansion-panel.hidden {
  height: 0;
  padding-top: 0;
  padding-bottom: 0;
  opacity: 0;
  transform: translateY(10px);
}

.expansion-panel .el-button {
  height: 38px; /* Slightly taller for better touch target */
  border-radius: 20px; /* More rounded corners for modern look */
  font-weight: 500;
  background-color: #f0f2f5; /* Light grey background */
  border: none; /* No border */
  color: #333; /* Darker text */
  padding: 0 15px; /* Add some padding */
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05); /* Subtle shadow */
  transition: all 0.2s ease;
}

.expansion-panel .el-button:hover {
  background-color: #e0e2e5; /* Darker on hover */
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1); /* More pronounced shadow on hover */
  transform: translateY(-1px);
}
</style>
